package com.chookss.video.model

import com.chookss.tools.MyEvent
import com.chookss.tools.MyToast
import com.chookss.tools.httpForm
import com.chookss.video.entity.VideoAuth
import com.chookss.video.response.GetVideoPlayAuthResponse
import org.greenrobot.eventbus.EventBus

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/20 17:35
 * Note:
 */
class GetPlayAuthImpl : IGetPlayAuth {

    private val cache = HashMap<String, MyAuth>()

    override fun call(videoId: String, action: (String, String, String, String) -> Unit) {
        var myAuth = cache[videoId]
        if (myAuth != null && myAuth.startTime + myAuth.auth.timeOut >= System.currentTimeMillis()+10) {
            action.invoke(videoId, myAuth.auth.playAuth,"",myAuth.auth.compeleteFlag)
            return
        }
        httpForm<GetVideoPlayAuthResponse> {
            url = "api/video/getVideoPlayAuth"
            params = mutableMapOf("videoId" to videoId)
            onSuccess = {

                cache[videoId] = MyAuth(System.currentTimeMillis(), it.data)
                action.invoke(videoId, it.data.playAuth,it.data.authId,it.data.compeleteFlag)

            }
            onError = {
                if(it.toString().contains("删除")){
                    MyToast.show(it.toString())
                    println("-------------")
                    EventBus.getDefault().post(MyEvent("DeleteVideo"))
                }
            }
        }
    }

    data class MyAuth(
        var startTime:Long,
        var auth: VideoAuth
    )
}